package cn.com.taiji.oospub.wechat.controller.servlet;


import cn.com.taiji.manager.ManagerException;
import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.oospub.wechat.common.HisAddressUtil;
import cn.com.taiji.oospub.wechat.common.authdeny.WeChatUtil;
import cn.com.taiji.oospub.wechat.common.authdeny.WeixinOauth2Token;
import cn.com.taiji.oospub.wechat.common.authdeny.XmlTools;
import cn.com.taiji.oospub.wechat.entity.*;
import cn.com.taiji.oospub.wechat.service.*;
import cn.com.taiji.pub.BeanTools;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Properties;

import static cn.com.taiji.oospub.wechat.common.Finals.PROPERTIES_PATH;
import static cn.com.taiji.oospub.wechat.common.wxpay.pay.Configure.requestGetMemberInfo;
import static java.net.URLEncoder.encode;

@WebServlet("/weixin/oosweb/welcome")
public class WeiXinAuthdenyLoginServlet extends HttpServlet {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    private ISystemLogService logManager;
    private ISnsuserinfoService sNSUserInfoManager;
    private IMemberBaseInfoService memberBaseInfoManager;
    private ISchoolBaseInfoService schoolManager;
    private IDiancanSchoolurlService dianCanSchoolUrlManager;
    private IRestaurantService restaurantService;
    private IReceiveAddressService receiveAddressService;
    private IAccesstokensaveService accesstokensaveService;
    private static RestTemplate restTemplate;
    private HisAddressUtil hisAddressUtil;
    private Properties props = new Properties();
    private String appID;
    private String appSecret;
    private String parentSpace;
    private String searchSpace;
    private String his_address_url;
    private InputStream inputStream;

    @Override
    public void init() throws ServletException {
        super.init();
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        logManager = wac.getBean(ISystemLogService.class);
        schoolManager = wac.getBean(ISchoolBaseInfoService.class);
        sNSUserInfoManager = wac.getBean(ISnsuserinfoService.class);
        memberBaseInfoManager = wac.getBean(IMemberBaseInfoService.class);
        schoolManager = wac.getBean(ISchoolBaseInfoService.class);
        dianCanSchoolUrlManager = wac.getBean(IDiancanSchoolurlService.class);
        restaurantService = wac.getBean(IRestaurantService.class);
        receiveAddressService = wac.getBean(IReceiveAddressService.class);
        accesstokensaveService = wac.getBean(IAccesstokensaveService.class);
        hisAddressUtil = wac.getBean(HisAddressUtil.class);
        restTemplate = wac.getBean(RestTemplate.class);
        try {
            inputStream = wac.getResource(PROPERTIES_PATH).getInputStream();
            props.load(inputStream);
            appID = props.getProperty("appID");
            appSecret = props.getProperty("appsecret");
            searchSpace = props.getProperty("searchSpace");
            parentSpace = props.getProperty("parentSpace");
            his_address_url = props.getProperty("his_address_url");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        doPost(req, resp);
    }

    @SuppressWarnings({"unused", "deprecation"})
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        resp.addHeader("Cache-Control", "no-cache, no-store");
        String spaceCode = "";
        String accountId = req.getParameter("accountId");
        if (accountId.contains("*")) {
            spaceCode = "{" + accountId.split("\\*")[1] + "}";
            accountId = accountId.split("\\*")[0];
            logger.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@{}", spaceCode);
        }
        String ip = XmlTools.getIpAddress(req);
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }

        logger.info("IP	[{}] 访问msmwxpub，项目ID	[{}]", ip, accountId);

        //1.通过网页授权获取的用户信息
        req.setCharacterEncoding("utf-8");
        // 用户同意授权后，能获取到code
        String code = req.getParameter("code");
        // 用户同意授权
        if (!"authdeny".equals(code)) {
            // 获取网页授权access_token
            System.out.println("appID++++++++++++++++++" + appID);
            System.out.println("appSecret++++++++++++++++++" + appSecret);
            WeixinOauth2Token weixinOauth2Token = WeChatUtil.getOauth2AccessToken(appID, appSecret, code);
            // 网页授权接口访问凭证
            String accessToken = weixinOauth2Token.getAccessToken();
            // 用户标识
            String openId = weixinOauth2Token.getOpenId();
            logger.info("--------用户openid:{}", openId);
            // 获取用户信息
            Snsuserinfo snsUserInfo = WeChatUtil.getSNSUserInfo(accessToken, openId);
            Snsuserinfo info = sNSUserInfoManager.findByProperty("openId", openId);
            MemberBaseInfo memberBaseInfo = memberBaseInfoManager.findByProperty("openid", openId);
            SchoolBaseInfo school = null;
            if (StringUtils.hasText(accountId)) {
                school = schoolManager.findByProperty("code", accountId);
            } else {
                try {
                    throw new ManagerException("不存在此餐厅");
                } catch (ManagerException e) {
                    e.printStackTrace();
                }
            }
            DiancanSchoolurl dianCanSchoolUrl = dianCanSchoolUrlManager.queryByCodeAndStatus(accountId, DiancanSchoolurl.IsEffect.YX);
            System.out.println("memberBaseInfo============" + memberBaseInfo);
            System.out.println("info============" + info);
            if (info == null && memberBaseInfo == null) {
                logger.info("Snsuserinfo和memberBaseInfo都是null,跳转注册页注册");
                sNSUserInfoManager.save(snsUserInfo);
                String saoma_register_url = dianCanSchoolUrl.getSchoolUrl() + "/#/Registers";
                saoma_register_url += "?accountId=" + accountId + "&openid=" + openId + "&projectName=" + encode(school.getNameZh(), "UTF-8") + "&spaceCode=" + spaceCode + "&time=" + System.currentTimeMillis();
                logger.info("用户未注册info:{},跳转注册页:{}", info, saoma_register_url);
                resp.sendRedirect(saoma_register_url);
            } else if (info != null && memberBaseInfo == null) {
                logger.info("snsUserInfo============" + snsUserInfo);
                logger.info("Snsuserinfo不是null-------memberBaseInfo是null,跳转注册页注册");
                BeanTools.copyProperties(snsUserInfo, info, "id");
                sNSUserInfoManager.updateById(info);
                // 设置要传递的参数   --注册页面
                String saoma_register_url = dianCanSchoolUrl.getSchoolUrl() + "/#/Registers";
                saoma_register_url += "?accountId=" + accountId + "&openid=" + openId + "&projectName=" + encode(school.getNameZh(), "UTF-8") + "&spaceCode=" + spaceCode + "&time=" + System.currentTimeMillis();
                logger.info("用户未注册info:{},跳转注册页:{}", info, saoma_register_url);
                resp.sendRedirect(saoma_register_url);
            } else if (info != null && memberBaseInfo != null) {
                logger.info("用户已经注册");
                if (!accountId.equals(memberBaseInfo.getSchool().getCode())) {
                    logger.info("用户注册schoolCode与项目schoolCode不一样");
                    String url = dianCanSchoolUrl.getSchoolUrl() + "/#/registerImg?time=" + System.currentTimeMillis();
                    resp.sendRedirect(url);
                } else {
                    BeanTools.copyProperties(snsUserInfo, info, "id");
                    sNSUserInfoManager.updateById(info);
                    if (MemberBaseInfo.MemberStatus.NORMAL.equals(memberBaseInfo.getStatus())) {
                        if (StringUtils.hasText(spaceCode)) {
                            List<ReceiveAddress> receiveAddressList = receiveAddressService.query()
                                    .eq("Member_Id", memberBaseInfo.getId())
                                    .eq("is_delete", false)
                                    .eq("Is_First", 1).orderByDesc("Create_Time").list();
                            try {
                                String architecture = hisAddressUtil.getArchitecture(spaceCode, 1);
                                System.out.println("searchSpace searchSpace searchSpace searchSpace" + searchSpace);
                                MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
                                paramMap.add("code", spaceCode);
                                paramMap.add("searchType", "1");
                                if (receiveAddressList.size() > 0) {
                                    ReceiveAddress receiveAddress = receiveAddressList.get(0);
                                    receiveAddress.setArchitecture(architecture);
                                    String address = restTemplate.postForObject(searchSpace, paramMap, String.class).replace("|", ",");
                                    if (address.split("#").length > 1) {
                                        receiveAddress.setAddress(address.split("#")[0].trim());
                                        receiveAddress.setHisSpaceID(address.split("#")[1].trim());
                                        if (StringUtils.isEmpty(memberBaseInfo.getPatientNumber()) && StringUtils.hasText(his_address_url)) {
                                            memberBaseInfo.setPatientNumber(hisAddressUtil.getHospitalNumberByHisSpaceId(receiveAddress.getHisSpaceID()));
                                            memberBaseInfoManager.updateById(memberBaseInfo);
                                        }
                                    } else {
                                        receiveAddress.setAddress(address.trim());
                                    }
                                    receiveAddressService.updateById(receiveAddress);
                                } else {
                                    ReceiveAddress receiveAddress = new ReceiveAddress();
                                    String address = restTemplate.postForObject(searchSpace, paramMap, String.class).replace("|", ",");
                                    if (address.split("#").length > 1) {
                                        receiveAddress.setAddress(address.split("#")[0].trim());
                                        receiveAddress.setHisSpaceID(address.split("#")[1].trim());
                                        if (StringUtils.isEmpty(memberBaseInfo.getPatientNumber()) && StringUtils.hasText(his_address_url)) {
                                            memberBaseInfo.setPatientNumber(hisAddressUtil.getHospitalNumberByHisSpaceId(receiveAddress.getHisSpaceID()));
                                            memberBaseInfoManager.updateById(memberBaseInfo);
                                        }
                                    } else {
                                        receiveAddress.setAddress(address.trim());
                                    }
                                    receiveAddress.setIsFirst("1");
                                    receiveAddress.setIsDelete(false);
                                    receiveAddress.setMemberId(memberBaseInfo.getId());
                                    receiveAddress.setTel(memberBaseInfo.getMobile());
                                    receiveAddress.setName(memberBaseInfo.getName());
                                    receiveAddress.setCreateTime(LocalDateTime.now());
                                    receiveAddress.setArchitecture(architecture);
                                    receiveAddressService.save(receiveAddress);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        QueryWrapper<Restaurant> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("is_stop", false);
                        queryWrapper.eq("school_id", memberBaseInfo.getSchoolId());
                        memberBaseInfo.setRestaurant(restaurantService.list(queryWrapper).get(0));
                        WebUtils.setSessionAttribute(req, SessionNames.LOGIN_USER, memberBaseInfo);

                        String url = requestGetMemberInfo.replace("OPENID", openId).replace("ACCESS_TOKEN", accesstokensaveService.query().one().getAccessToken());
                        JSONObject result = JSONObject.parseObject(HttpUtil.get(url));
                        System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" + result);
                        String gzh_login_url = dianCanSchoolUrl.getSchoolUrl() + "/#/home";
                        if (result != null) {
                            if ("1".equals(result.getString("subscribe"))) {
                                //已关注
                                gzh_login_url = gzh_login_url + "?openid=" + info.getOpenId() + "&ZhOrEn=" + encode(memberBaseInfo.getZhOrEn().getValue(), "UTF-8") + "&time=" + System.currentTimeMillis();
                                logger.info("跳转点餐首页url:{}", gzh_login_url);
                                resp.sendRedirect(gzh_login_url);
                            } else {
                                gzh_login_url = dianCanSchoolUrl.getSchoolUrl() + "/#/registerImg?time=" + System.currentTimeMillis();
                                logger.info("跳转registerImg    url:{}", gzh_login_url);
                                resp.sendRedirect(gzh_login_url);
                            }
                        } else {
                            gzh_login_url = dianCanSchoolUrl.getSchoolUrl() + "/#/registerImg?time=" + System.currentTimeMillis();
                            logger.info("跳转registerImg  22222222222222222   url:{}", gzh_login_url);
                            resp.sendRedirect(gzh_login_url);
                        }
                    } else {
                        logger.info("用户已经注册,但是被拉黑");
                        String url = dianCanSchoolUrl.getSchoolUrl() + "/#/registerImg?time=" + System.currentTimeMillis();
                        resp.sendRedirect(url);
                    }
                }
            }
        }
    }
}